package com.coder520.sync_learning.demo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Cache {
	static Map<String, Object> map=new HashMap<String, Object>();
	static ReentrantReadWriteLock rwl=new ReentrantReadWriteLock();
	static Lock rLock=rwl.readLock();
	static Lock wLock=rwl.writeLock();
	/**
	 * 获取一个key对应的value
	 * @param key
	 * @return
	 *	2018年6月13日
	 */
	public static final Object get(String key) {
		// TODO Auto-generated method stub
		rLock.lock();
		try {
			return map.get(key);
		}finally {
			rLock.unlock();
		}
	}
	
	/**
	 * 设置key对应的value，并且返回旧的value
	 * @param key
	 * @param value
	 * @return
	 *	2018年6月13日
	 */
	 public static final  Object put(String key,Object value) {
		// TODO Auto-generated method stub
		 wLock.lock();
		 try {
			return map.put(key, value);
		} finally {
			// TODO: handle finally clause
			wLock.unlock();
		}
	}
	
	 public static final void clear() {
		// TODO Auto-generated method stub
		 wLock.lock();
		 try {
			map.clear();
		} finally {
			// TODO: handle finally clause
			wLock.unlock();
		}
	}
}
